package com.ruoyi.web.controller.protocol;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.shop.protocol.sse.SseServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-06-27  19:37
 */
@Slf4j
@RestController
@RequestMapping("/sse")
public class SseController {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CacheProperties cacheProperties;

    @GetMapping("/order-total")
    public SseEmitter getOrderTotal(HttpServletResponse response) throws Exception {
        response.setContentType("text/event-stream");
        String id = UUID.randomUUID().toString();
        SseEmitter emitter = SseServer.createConnection(id);

        // 每隔3秒查询redis并发送一次数据
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    log.error("线程中断异常", e);
                }
                SseServer.sendMessage(id, "order-total:" + redisCache.getCacheObject("order_total"));
            }
        }).start();
        return emitter;
    }
}
